import 'package:dsbridge_flutter/dsbridge_flutter.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

// ignore: depend_on_referenced_packages
import 'package:webview_flutter/webview_flutter.dart';
// ignore: depend_on_referenced_packages
import 'package:webview_flutter_ohos/webview_flutter_ohos.dart' as ohos_web;
// ignore: depend_on_referenced_packages
import 'package:webview_flutter_android/webview_flutter_android.dart'
    as android_web;
// ignore: depend_on_referenced_packages
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart'
    as ios_web;

import 'js_bridge.dart';

class UnvWebview extends StatefulWidget {
  const UnvWebview({super.key, required this.url});
  final String url;
  @override
  State<UnvWebview> createState() => _UnvWebviewState();
}

class _UnvWebviewState extends State<UnvWebview> {
  late final DWebViewController webViewController;
  late final JsBridge bridge;

  @override
  void initState() {
    super.initState();
    bridge = JsBridge(
      openURL: openURL,
      backURL: backURL,
    );
    webViewController = DWebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(_delegate())
      ..addJavaScriptObject(bridge);
    // if (kDebugMode) {
    /// 开启debug调试
    if (TargetPlatform.ohos == defaultTargetPlatform) {
      ohos_web.OhosWebViewController.enableDebugging(true);
    } else if (TargetPlatform.android == defaultTargetPlatform) {
      android_web.AndroidWebViewController.enableDebugging(true);
    }
    if (TargetPlatform.iOS == defaultTargetPlatform) {
      (webViewController.platform as ios_web.WebKitWebViewController)
          .setInspectable(true);
      debugPrint("${webViewController.platform}");
    }
    // }
    webViewController.loadFlutterAsset("assets/${widget.url}");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      // extendBodyBehindAppBar: true,
      // appBar: AppBar(
      //   title: const Text("本地网页"),
      //   centerTitle: true,
      //   elevation: 0,
      // ),
      body: SafeArea(
          child: WebViewWidget(
        controller: webViewController,
      )),
    );
  }

  NavigationDelegate _delegate() {
    return NavigationDelegate(
      onNavigationRequest: (request) {
        debugPrint(request.url);
        return NavigationDecision.navigate;
      },
      onPageStarted: (url) {
        debugPrint("start $url");
      },
      onProgress: (progress) {
        debugPrint("progress $progress");
      },
      onPageFinished: (url) {
        debugPrint("finish $url");
      },
      onWebResourceError: (error) {
        debugPrint(
            "err ${error.description}  ${error.errorCode} ${error.errorType} ${error.url}");
      },
    );
  }

  void openURL(String url, {String? title, String? query}) {
    Widget newPage;
    if (url.startsWith("http://") || url.startsWith("https://")) {
      newPage = Webview(
        url: url,
      );
    } else {
      if (query != null) {
        url = url + query;
      }
      newPage = UnvWebview(
        url: url,
      );
    }
    debugPrint(url);
    Get.to(() => newPage, routeName: "$url ${DateTime.now().toString()}");
  }

  void backURL({
    bool? main,
    String? url,
    Map<String, dynamic>? params,
    String? title,
  }) {
    if (main == true) {
      Get.until((route) => route.isFirst);
    } else if (url == null) {
      Get.back();
    }
  }
}

class Webview extends StatefulWidget {
  const Webview({super.key, required this.url, this.title});
  final String url;
  final String? title;
  @override
  State<StatefulWidget> createState() => _WebviewState();
}

class _WebviewState extends State<Webview> {
  late final WebViewController webViewController;
  @override
  void initState() {
    super.initState();
    webViewController = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted);
    webViewController.loadRequest(Uri.parse(widget.url));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        foregroundColor: Colors.black,
        elevation: 0.5,
        title: Text(widget.title ?? ''),
        centerTitle: true,
        leading: IconButton(
            onPressed: () {
              Navigator.pop(context);
            },
            icon: const Icon(
              Icons.arrow_back_ios_rounded,
              color: Colors.black,
            )),
      ),
      body: WebViewWidget(controller: webViewController),
    );
  }
}
